<template>
  <div class="edit-shops-container">
    <el-form
      ref="shopFormRef"
      label-position="left"
      label-width="100px"
      :model="formModel"
    >
      <section class="info-content">
        <xm-card-header title="基本信息"></xm-card-header>
        <el-form-item
          label="商品图片："
          class="fix_image"
          props="images"
          :rules="uploadRules"
        >
          <!--          <file-upload-->
          <!--            v-model="formModel.imagesJson"-->
          <!--            type="picture-card"-->
          <!--            :drag="false"-->
          <!--            ref="updataImageRef"-->
          <!--            :max="15"-->
          <!--            :rules="uploadRules"-->
          <!--          ></file-upload> @change="onImgUploadChange"-->
          <ImgUpload
            ref="updataImageRef"
            :maxSize="3000"
            :multiple="true"
            v-model="formModel.imagesJson"
            :limit="15"
          />
          <div>建议尺寸：800*800像素，大小3MB，最多上传15张</div>
          <!-- <div></div> -->
        </el-form-item>

        <el-form-item label="主图视频：" props="videoUrl">
          <!--          <file-upload-->
          <!--            v-model="formModel.videoObj"-->
          <!--            type="picture-card"-->
          <!--            :drag="false"-->
          <!--            ref="updataVideoRef"-->
          <!--            :maxFileSize="15"-->
          <!--            file-accept="video/*"-->
          <!--          ></file-upload>-->
          <ImgUpload
            v-model="formModel.videoObj"
            ref="updataVideoRef"
            :limit="1"
            :maxSize="15360"
            :is-video="true"
          />
        </el-form-item>

        <XmFIntput
          quick
          v-model="formModel.title"
          prop="title"
          label="商品标题:"
          :maxlength="180"
        ></XmFIntput>

        <XmFIntput
          quick
          v-model="formModel.summary"
          prop="summary"
          label="商品卖点:"
          :maxlength="200"
        ></XmFIntput>

        <XmFIntput
          quick
          v-model="formModel.shareDesc"
          prop="shareDesc"
          label="分享描述:"
          :maxlength="200"
        ></XmFIntput>

        <xm-f-select
          quick
          prop="goodsTypeIdString"
          isMultiple
          label="商品分类:"
          v-model="formModel.goodsTypeIdString"
          :options="goodsTypeSels"
        ></xm-f-select>

        <xm-f-select
          prop="saleTypeIdString"
          isMultiple
          label="营销分类:"
          v-model="formModel.saleTypeIdString"
          :options="salesTypeSels"
        ></xm-f-select>
      </section>
      <section class="info-content">
        <xm-card-header title="型号/价格">
          <template #right>
            <el-radio-group
              v-model="shopAddType"
              style="margin-bottom: 30px"
              @change="groupChange"
            >
              <el-radio-button label="Single">单规格</el-radio-button>
              <el-radio-button label="Multiple">多规格</el-radio-button>
            </el-radio-group>
          </template>
        </xm-card-header>
        <template v-if="shopAddType === 'Single'">
          <XmFIntput
            quick
            v-model="formModel.costPrice"
            prop="costPrice"
            label="成本价:"
            v-number:2
            placeholder="单位(元)，最多输入两位小数"
          ></XmFIntput>

          <XmFIntput
            quick
            v-model="formModel.retailPrice"
            prop="retailPrice"
            label="零售价:"
            v-number:2
            placeholder="单位(元)，最多输入两位小数"
          ></XmFIntput>

          <XmFIntput
            quick
            v-model="formModel.price"
            prop="price"
            label="实际售价:"
            v-number:2
            placeholder="单位(元)，最多输入两位小数"
            bottom="仓库货品数据中设置的为零售价（划线价），若需要设置优惠价格请在本栏填写实际售价"
          ></XmFIntput>

          <XmFIntput
            quick
            v-model="formModel.stock"
            v-number
            prop="stock"
            label="商品库存:"
            placeholder="单位(个)，输入整数"
          ></XmFIntput>
          <!-- 商品重量和编码 一个算邮费一个分单规格和多规格 -->
          <XmFIntput
            quick
            v-model="formModel.weight"
            v-number:2
            prop="weight"
            label="商品重量:"
            placeholder="单位(kg)，最多输入两位小数"
          ></XmFIntput>

          <XmFIntput
            quick
            v-model="formModel.goodsCode"
            prop="goodsCode"
            label="商品编码:"
          ></XmFIntput>
        </template>
        <template v-else>
          <el-form-item label="商品规格：" required>
            <commoditySpecifications
              :initData="sectionData"
              @addSpec="addSpec"
              @editSpec="editSpec"
              @deteleCell="deteleCell"
              @sectionTitleChange="sectionTitleChange"
            ></commoditySpecifications>
          </el-form-item>
          <el-form-item>
            <shopAndSpecificationDetails
              :tableDatas="tableDatas"
              :spanMergeDic="spanMergeDic"
              :sectionData="sectionData"
            ></shopAndSpecificationDetails>
          </el-form-item>
          <XmFIntput
            quick
            v-model="formModel.weight"
            prop="weight"
            label="商品重量:"
            v-number:2
            placeholder="单位(kg)，最多输入两位小数"
          ></XmFIntput>

          <XmFIntput
            quick
            v-model="formModel.retailPrice"
            prop="retailPrice"
            label="零售价:"
            v-number:2
            placeholder="单位(元)，最多输入两位小数"
          ></XmFIntput>
        </template>
      </section>
      <section class="info-content">
        <xm-card-header title="售卖设置"></xm-card-header>
        <xm-f-radio
          quick
          prop="status"
          v-model="formModel.status"
          label="上下架设置:"
          :options="UpAndLowerShelves"
        >
          <div
            v-if="isSell"
            style="white-space: pre-wrap; width: 100%; color: #a8abb2"
          >
            已售罄，请添加库存后再进行操作。
          </div>
        </xm-f-radio>
      </section>
      <section class="info-content">
        <xm-card-header title="商品详情"></xm-card-header>
        <EditorVue
          v-model="formModel.description"
          @change="handleChange"
          width="100%"
        ></EditorVue>
      </section>
    </el-form>
    <section class="info-content foot">
      <el-button type="primary" @click="toSave">保存</el-button>
      <el-button @click="toBack">取消</el-button>
    </section>
  </div>
</template>
<script lang="ts" setup>
  import FileUpload from '@/components/FileUpload/index.vue'
  import ImgUpload from '@/components/ImgUpload/index.vue'
  // eslint-disable-next-line max-len
  import commoditySpecifications from '../../components/commoditySpecifications/index.vue'
  // eslint-disable-next-line max-len
  import shopAndSpecificationDetails from '../../components/shopAndSpecificationDetails/index.vue'
  import EditorVue from '@/components/Tinymce/src/Editor.vue'
  import { shop } from '@/types/shop'
  import { ref } from 'vue'
  import {
    getSaleTypes,
    getGoodsTypes,
    saveGoods,
    getGoodsInfoWithSpuId,
  } from '@/api/modules/shop'
  import common from '@/utils/common'
  import { usePromise } from '@/hooks/core/usePromise'
  import { onMountedOrActivated } from '@/hooks/core/onMountedOrActivated'
  import XmFSelect from '@/components/XMC/XmForms/XmFSelect/index.vue'
  import useEditShop from '@/views/shops/components/hooks/useEditShop'
  import { useRoute, useRouter } from 'vue-router'
  import { useStore } from 'vuex'
  // const dataJson = require('../../datas/goods example1.json')
  const testJson = require('../../datas/test.json')
  // dataJson.specInfoParamList
  const {
    initDatas,
    spanMergeDic,
    tableDatas,
    sectionData,
    addSectionUpdateTableDatas,
    editSectionUpdateTableDatas,
    deteleTableCell,
    editSectionTitle,
    clearDatas,
    packNetData,
    loadDataConverSubmitData,
  } = useEditShop()

  const route = useRoute()
  const router = useRouter()
  const store = useStore()
  onMountedOrActivated(() => {
    if (route.query.id) {
      initDatas([])
    } else {
      formModel.value.imagesJson = []
      formModel.value.videoObj = []
    }
    store.dispatch('emr/setEditingStatus', true)
  })

  // const isMultiple = computed(() => {
  //   if (formModel.value.goodsCode) return true
  //   return false
  // })
  function addSpec(item: any) {
    const { value, index, sectionTitle } = item
    addSectionUpdateTableDatas({ ...value }, index, sectionTitle)
  }

  function editSpec(item: any) {
    const { value, index, sectionTitle } = item
    editSectionUpdateTableDatas({ ...value }, index, sectionTitle)
  }
  const { to } = usePromise()
  const formModel = ref<Partial<shop>>({})
  const shopFormRef = ref()
  // 页面类型 Multiple Single
  const shopAddType = ref('Single')

  onMountedOrActivated(() => {
    // 加载显示的分类
    loadTypeSels(1)
    loadTypeSels(2)
  })
  const salesTypeSels = ref([])
  const goodsTypeSels = ref([])
  // type === 1 是营销分类
  async function loadTypeSels(type: number) {
    const [err, res] =
      type === 1
        ? await to(getSaleTypes({} as any))
        : await to(getGoodsTypes({} as any))
    if (!err) {
      const convert = function () {
        return res.data.map((item: any) => {
          return { label: item.name, value: item.id + '' }
        })
      }

      type === 1
        ? (salesTypeSels.value = convert())
        : (goodsTypeSels.value = convert())
    }
  }

  const title = ref()
  const UpAndLowerShelves = [
    { label: '上架售卖', value: 1 },
    { label: '暂不上架', value: 0 },
  ]

  const value = ref('')
  const handleChange = function (val: any) {
    console.log('val' + val)
    console.log('value' + value.value)
  }

  const validF = function (rules: any, value: any, cb: Function) {
    if (!Array.isArray(JSON.parse(value)) || JSON.parse(value).length < 1) {
      cb(new Error('至少上传一张'))
    }
    cb()
  }

  const uploadRules = [
    { required: true, message: '不能为空' },
    { required: true, validator: validF },
  ]

  const updataImageRef = ref()
  const updataVideoRef = ref()
  function toSave() {
    const uploadedToImg: Boolean = updataImageRef.value.isUploading
    const uploadedToVideo: Boolean = updataVideoRef.value.isUploading

    if (uploadedToImg || uploadedToVideo) {
      common.XmMessage(1, '正在上传图片或视频')
      return
    }
    shopFormRef.value.validate(async (valid: boolean, msg: string) => {
      if (valid) {
        const tmp: any = { ...formModel.value }
        // if (shopAddType.value === 'Multiple')
        if (tmp.goodsTypeIdString) {
          tmp.goodsTypeIds = tmp.goodsTypeIdString.split(',')
        }
        if (tmp.saleTypeIdString) {
          tmp.saleTypeIds = tmp.saleTypeIdString.split(',')
        }
        // 千克转成克
        tmp.weight = tmp.weight * 100
        // 多规格需要特殊处理下
        if (shopAddType.value === 'Multiple') {
          const { costPrice, num, price, convertAfter } = packNetData()
          // 总成本价
          tmp.costPrice = costPrice
          // 总实际售价
          tmp.price = price
          // 总库存
          tmp.stock = num
          // 产出编码
          tmp.goodsCode = ''
          // 零售价
          tmp.retailPrice = parseFloat(tmp.retailPrice) * 100
          tmp.specInfoParamList = convertAfter
          let isCompleteWithList =
            Array.isArray(convertAfter) && convertAfter.length > 0

          for (let i = 0; i < convertAfter.length; i++) {
            const { costPrice, price, num } = convertAfter[i]
            if (!costPrice || !price || !num) {
              isCompleteWithList = false
              break
            }
          }
          if (!isCompleteWithList) {
            common.XmMessage(1, '请添加或补完商品规格必填项')
            return
          }
        } else {
          // 删除以匹配复显后保存
          delete tmp.specInfos
          delete tmp.specInfoParamList
          tmp.costPrice = parseFloat(tmp.costPrice) * 100
          tmp.price = parseFloat(tmp.price) * 100
          tmp.retailPrice = parseFloat(tmp.retailPrice) * 100
        }
        tmp.status = UpAndLowerShelves.find(
          (item) => item.label === tmp.status + ''
        )?.value
        // tmp.images = JSON.parse(tmp.imagesJson)
        tmp.images = tmp.imagesJson
        if (tmp.videoObj.length > 0) {
          tmp.videoUrl = tmp.videoObj[0].url
          tmp.videoImg = tmp.videoObj[0].coverUrl
        }
        // if (tmp.videoObj) {
        //   const urls = JSON.parse(tmp.videoObj)
        //   if (urls.length > 0) tmp.videoUrl = urls[0].url
        // }

        common.XmLoading(true)
        const [err, res] = await to(saveGoods(tmp))
        common.XmLoading()
        if (!err) {
          common.XmMessage(0, route.query.id ? '修改商品成功' : '创建商品成功')
          toBack()
        }
      }
    })
  }

  function toBack() {
    // 兼容路由守卫 放行
    store.dispatch('emr/setEditingStatus', false)
    router.go(-1)
  }

  onMountedOrActivated(() => {
    if (route.query.id) loadData()
  })

  const isSell = ref(false)
  async function loadData() {
    const [err, res] = await to(getGoodsInfoWithSpuId(route.query.id as any))
    if (res) {
      if (res.data) {
        const tmp = res.data
        // tmp.imagesJson = JSON.stringify(tmp.images)
        tmp.imagesJson = tmp.images ? tmp.images : []
        if (tmp.status === 2) isSell.value = true
        tmp.status = UpAndLowerShelves.find(
          (item) => item.value + '' === tmp.status + ''
        )?.label

        tmp.saleTypeIdString = tmp.saleTypeIds.join(',')
        tmp.goodsTypeIdString = tmp.goodsTypeIds.join(',')

        if (tmp.videoUrl) {
          tmp.videoObj = [
            { name: 'videoObj', url: tmp.videoUrl, coverUrl: tmp.videoImg },
          ]
        } else {
          tmp.videoObj = []
        }

        formModel.value = tmp
        if (formModel.value.goodsCode) {
          shopAddType.value = 'Single'
          tmp.costPrice = tmp.costPrice / 100
          tmp.price = tmp.price / 100
          tmp.retailPrice = tmp.retailPrice / 100
          tmp.weight = tmp.weight / 100
        } else {
          shopAddType.value = 'Multiple'
          tmp.costPrice = tmp.costPrice / 100
          tmp.price = tmp.price / 100
          tmp.retailPrice = tmp.retailPrice / 100
          tmp.specInfoParamList = loadDataConverSubmitData(res.data)
          tmp.weight = tmp.weight / 100
          initDatas(tmp.specInfoParamList)
        }
        if (isSell.value) {
          common.XmAlert(
            '该商品已售罄，在添加库存前只能进行下架操作。',
            () => {}
          )
        }
      }
    }
  }

  function deteleCell(value: any) {
    const { sectionIndex, cellIndex, text } = value
    deteleTableCell(sectionIndex, text)
  }

  function sectionTitleChange(value: any) {
    const { text, index } = value
    editSectionTitle(text, index)
  }

  // 切换时清空多余的数据
  function groupChange(value: any) {
    // if (value === 'Multiple') {
    //   // @ts-ignore：无法被执行的代码的错误
    //   formModel.value.costPrice = null
    //   // @ts-ignore：无法被执行的代码的错误
    //   formModel.value.retailPrice = null
    //   // @ts-ignore：无法被执行的代码的错误
    //   formModel.value.price = null
    //   // @ts-ignore：无法被执行的代码的错误
    //   formModel.value.stock = null
    //   // @ts-ignore：无法被执行的代码的错误
    //   formModel.value.weight = null
    //   // @ts-ignore：无法被执行的代码的错误
    //   formModel.value.goodsCode = null
    // } else {
    //   clearDatas()
    // }
  }
</script>
<style lang="scss" scoped>
  .edit-shops-container {
    .info-content {
      margin: 22px;
      background-color: white;
      padding: 22px;
    }
    .fix_image {
      :deep(.el-form-item__content) {
        flex-direction: column;
        align-items: baseline;
      }
    }

    .info-content {
      margin: 22px;
      background-color: white;
      padding: 15px;
      .foots {
        margin: 0 24px;
      }
    }
    .foot {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
